package com.heima.datasync.service.impl;

import com.google.common.collect.Lists;
import com.heima.common.constants.search.SearchConstants;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    EsService<SearchArticleVO> esService;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult dataInit() {
        // 1. 判断索引库是否存在
        boolean isHas = esService.existIndex(SearchConstants.APP_ARTICLE_INDEX);
        if(isHas){
            // 2. 如果存在  删除索引库
            esService.deleteIndex(SearchConstants.APP_ARTICLE_INDEX);
        }
        // 3. 创建索引库
        esService.createIndex(SearchConstants.APP_ARTICLE_INDEX_MAPPING,SearchConstants.APP_ARTICLE_INDEX);
        // 4. 从数据库中查询文章数据
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        // 5. 将List<ApArticle>集合 转为 List<SearchArticleVO>
        List<SearchArticleVO> searchArticleVOList = allArticles.stream()
                .map(article -> {
                    SearchArticleVO articleVO = new SearchArticleVO();
                    BeanUtils.copyProperties(article, articleVO);
                    return articleVO;
                }).collect(Collectors.toList());
        // 6. 批量保存文章数据到es索引库  控制5000个文档
        List<List<SearchArticleVO>> partitions = Lists.partition(searchArticleVOList, 5000);
        for (List<SearchArticleVO> partitionList : partitions) {
            esService.saveBatch(partitionList,SearchConstants.APP_ARTICLE_INDEX);
        }
        return ResponseResult.okResult();
    }
}
